﻿namespace SyncAndAsync
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("同步输出开始");
            SyncOutput();
            Console.WriteLine("同步输出结束");

            Console.WriteLine("异步输出开始");
            await AsyncOutput();
            Console.WriteLine("异步输出结束");
        }

        /// <summary>
        /// 同步输出
        /// </summary>
        static void SyncOutput()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(i);
            }
        }

        /// <summary>
        /// 异步输出
        /// </summary>
        static async Task AsyncOutput()
        {

            // 使用Task数组并行执行异步任务
            Task[] tasks = new Task[5];

            for (int i = 0; i < 5; i++)
            {
                int number = i;
                tasks[i] = Task.Run(async () =>
                {
                    // 模拟异步操作，延迟随机时间
                    Random random = new Random();
                    int delayMilliseconds = random.Next(100, 1000);
                    await Task.Delay(delayMilliseconds);

                    // 输出无序数字
                    Console.WriteLine(number);
                });
            }

            // 等待所有异步任务完成
            await Task.WhenAll(tasks);

        }
    }
}